<?php namespace App\Http\Controllers\Api\Admin;

use App\Admin;
use App\Banner;
use App\BooksChapter;
use App\BooksInfo;
use App\Classify;
use App\Company;
use App\CompanyManager;
use App\Http\Controllers\Controller;
use App\Http\Services\Wechat\WechatLogin;
use App\Permission;
use App\PointItem;
use App\PointItemImg;
use App\project;
use App\ProjectUsers;
use App\RechargePackage;
use App\Role;
use App\Status;
use App\SteelFormat;
use App\SteelFormatAssociation;
use App\SystemInfo;
use App\TemplateMessage;
use App\User;
use App\UserInfo;
use App\VipRule;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SystemController extends Controller
{
    public function setBanner(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $title   = $request->get('title');
        $linkUrl = $request->get('link_url');
        $sort    = $request->get('sort');
        $imgId   = $request->get('img_id');
        $id      = !is_null($request->get('id'))?$request->get('id'):0;

        $thatBanner = Banner::whereId(trim($id))->first();

        if(!$thatBanner)
            $thatBanner = new Banner();

        if(!is_null($title))$thatBanner->title = $title;
        if(!is_null($linkUrl))$thatBanner->link_url = $linkUrl;
        if(!is_null($sort))$thatBanner->sort = $sort;
        if(!is_null($imgId))$thatBanner->img_id = $imgId;
        $thatBanner->save();

        return response()->json(["level"=>"success","message"=>"添加或修改成功","data"=>$thatBanner]);
    }

    public function delBanner(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        /** @var Banner $thatBanner */
        $thatBanner = Banner::whereId($id)->first();

        if(!$thatBanner)
            return response()->json(["level"=>"error","message"=>"该banner不存在！"]);

        $thatBanner->delete();

        return response()->json(["level"=>"success","message"=>"删除成功","data"=>$thatBanner]);
    }

    public function setAdmin(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $username = $request->get('username');
        $password = $request->get('password');
        $repass   = $request->get('repass');

        if($password != $repass)
            return response()->json(['level'=>'error','message' => '两次密码不一致！']);

        /** @var Admin $hasUser */
        $hasUser = Admin::whereUsername($username)->first();
        if($hasUser){
            return response()->json(['level'=>'error','message' => '当前管理员账号已存在']);
        }

        $thatAdmin = new Admin();
        $thatAdmin->username = $username;
        $thatAdmin->password = bcrypt($password);
        $thatAdmin->status = 2;
        $thatAdmin->save();

        return response()->json(['level'=>'success','message'=>'添加成功','data'=>$thatAdmin]);
    }

    public function delAdmin(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        /** @var Admin $thatAdmin */
        $thatAdmin = Admin::whereId($id)->first();

        if(!$thatAdmin)
            return response()->json(["level"=>"error","message"=>"该管理员不存在！"]);

        if($thatAdmin->status == 1)
            return response()->json(["level"=>"error","message"=>"该管理员不能删除！"]);


        $thatAdmin->forceDelete();

        return response()->json(["level"=>"success","message"=>"删除成功","data"=>$thatAdmin]);
    }

    public function addClassify(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $name = $request->get("name");
        $sort = $request->get('sort');
        $id   = !is_null($request->get('id'))?$request->get('id'):0;

        $newClassify = Classify::whereId(trim($id))->first();

        if(!$newClassify)
            $newClassify = new Classify();

        if(!is_null($name))$newClassify->name = $name;
        if(!is_null($sort))$newClassify->sort = $sort;
        $newClassify->save();

        return response()->json(["level"=>"success","message"=>"添加或修改成功","data"=>$newClassify]);
    }

    public function delClassify(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;
        $thatClassify =Classify::whereId($id)->first();

        if(!$thatClassify)
            return response()->json(["level"=>"error","message"=>"该分类不存在！"]);

        $thatClassify->delete();

        return response()->json(['level' => 'success','message' => '删除成功']);
    }

    public function setUserInfoRemark(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $description   = !is_null($request->get('description')) ? $request->get('description') : '';
        $id            = !is_null($request->get('id'))?$request->get('id'):0;

        $thatUser = UserInfo::whereUserId(trim($id))->first();

        if(!$thatUser)
            $thatUser = new UserInfo();

        $thatUser->description   = $description;
        $thatUser->save();

        return response()->json(["level"=>"success","message"=>"设置成功","data"=>$thatUser]);
    }

    public function setAuthorization(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var UserInfo $thisUserInfo */
        $thisUserInfo = UserInfo::whereUserId($id)->first();
        if(!$thisUserInfo)
            return response()->json(['level' => 'error','message' => '用户信息不存在']);

        if($thisUserInfo->authorization == 0){
            $thisUserInfo->authorization = 1;
        }else{
            $thisUserInfo->authorization = 0;
        }

        $thisUserInfo->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $thisUserInfo]);
    }

    public function setProjectStatus(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id     = !is_null($request->get('id')) ? $request->get('id') : 0;
        $status = !is_null($request->get('status')) ? $request->get('status') : 0;

        /** @var project $thisProject */
        $thisProject = project::whereId($id)->first();
        if(!$thisProject)
            return response()->json(['level' => 'error','message' => '项目不存在']);

        $thisProject->status = $status;
        $thisProject->save();

        if($thisProject && $thisProject->status == 1){
            /** @var User $thisUser */
            $thisUser = User::whereId($thisProject->user_id)->first();
            if(!$thisUser)
                return response()->json(['level' => 'error','message' => '项目的创建者不存在']);

            /** @var UserInfo $thisUserInfo */
            $thisUserInfo = UserInfo::whereUserId($thisUser->id)->first();
            if(!$thisUserInfo)
                return response()->json(['level' => 'error','message' => '项目的创建者信息不存在']);

            /** @var TemplateMessage $templateMessage */
            $templateMessage = TemplateMessage::whereUserId($thisUser->id)->whereStatus(0)->orderBy('created_at','desc')->first();
            if((strtotime($templateMessage->created_at) + (7 * 24 * 3600)) > time()){
                $result = WechatLogin::wxSendTemplateMessage($thisUser->wx_openid,$templateMessage->form_id,$thisProject->id,$thisProject->name,$thisUserInfo->nickname,'已完成');
                if($result->errmsg == "ok"){
                    $templateMessage->status = 1;
                    $templateMessage->save();
                }else{
                    return response()->json(['level' => 'error','message' => '模版消息发送失败','data' => $result]);
                }
            }
        }

        return response()->json(['level' => 'success','message' => '设置成功','data' => $thisProject]);
    }

    public function userCheckComplete(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id     = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var PointItem $thatPointItem */
        $thatPointItem = PointItem::whereId($id)->first();
        if(!$thatPointItem)
            return response()->json(['level'=>'error','message' => '数据未找到！']);

        $thatPointItemLastNum      = PointItemImg::wherePointItemId($thatPointItem->id)->sum("last_num");
        $thatPointItemUserCheckNum = PointItemImg::wherePointItemId($thatPointItem->id)->sum("user_check_num");

        $thatPointItem->last_num = $thatPointItemLastNum;
        $thatPointItem->user_check_num = $thatPointItemUserCheckNum;
        $thatPointItem->status = 2;
        $thatPointItem->save();

        /** @var project $project */
        $project = project::whereId($thatPointItem->project_id)->first();
        if($project){
            $pointItem   = PointItem::whereProjectId($project->id)->whereType('submit_directly')->count();
            $pointItemOk = PointItem::whereProjectId($project->id)->whereType('submit_directly')->whereStatus(2)->count();

            if($pointItem <= $pointItemOk){
                $project->status = 1;
                $project->save();

                /** @var User $thisUser */
                $thisUser = User::whereId($project->user_id)->first();
                if(!$thisUser)
                    return response()->json(['level' => 'error','message' => '项目的创建者不存在']);

                /** @var UserInfo $thisUserInfo */
                $thisUserInfo = UserInfo::whereUserId($thisUser->id)->first();
                if(!$thisUserInfo)
                    return response()->json(['level' => 'error','message' => '项目的创建者信息不存在']);


                /** @var TemplateMessage $templateMessage */
                $templateMessage = TemplateMessage::whereUserId($thisUser->id)->whereStatus(0)->orderBy('created_at','desc')->first();
                if((strtotime($templateMessage->created_at) + (7 * 24 * 3600)) > time()){
                    $result = WechatLogin::wxSendTemplateMessage($thisUser->wx_openid,$templateMessage->form_id,$project->id,$project->name,$thisUserInfo->nickname,'已完成');
                    if($result->errmsg == "ok"){
                        $templateMessage->status = 1;
                        $templateMessage->save();

                    }else{
                        return response()->json(['level' => 'error','message' => '模版消息发送失败','data' => $result]);
                    }
                }
            }else{
                $project->status = 0;
                $project->save();
            }
        }else{
            return response()->json(['level' => 'error','message' => '项目不存在']);
        }


        return response()->json(['level' => 'success','message' => '完成处理','data' => $thatPointItem]);
    }

    public function setAutoCheck(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $thatSystemAutoCheck = SystemInfo::whereKey("auto_check")->first();
        if(!$thatSystemAutoCheck)
            return response()->json(['level' => 'error','message' => '该系统配置项不存在']);

        if($thatSystemAutoCheck->value == "0"){
            $thatSystemAutoCheck->value = "1";
        }else{
            $thatSystemAutoCheck->value = "0";
        }

        $thatSystemAutoCheck->save();

        return response()->json(['level' => 'success','message' => '设置成功']);
    }

    public function setManualCheck(Request $request){
        if(Auth::guard('admin')->guest())
            return response()->json(['level' => 'error','message' => '请先登录!']);

        /** @var SystemInfo $thisSystemManualCheck */
        $thisSystemManualCheck = SystemInfo::whereKey('manual_check')->first();
        if(!$thisSystemManualCheck)
            return response()->json(['level' => 'error','message' => '该系统配置项不存在']);

        if($thisSystemManualCheck->value == "0"){
            $thisSystemManualCheck->value = "1";
        }else{
            $thisSystemManualCheck->value = "0";
        }

        $thisSystemManualCheck->save();

        return response()->json(['level' => 'success','message' => '设置成功']);
    }


    public function setFree(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var UserInfo $thisUserInfo */
        $thisUserInfo = UserInfo::whereUserId($id)->first();
        if(!$thisUserInfo)
            return response()->json(['level' => 'error','message' => '用户信息不存在']);

        if($thisUserInfo->free == 0){
            $thisUserInfo->free = 1;
        }else{
            $thisUserInfo->free = 0;
        }

        $thisUserInfo->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $thisUserInfo]);
    }

    public function addVipRule(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $name          = $request->get("name");
        $type          = $request->get('type');
        $free          = $request->get('free');
        $price         = !is_null($request->get('price')) ? $request->get('price') : 0;
        $originalPrice = !is_null($request->get('original_price')) ? $request->get('original_price') : 0;
        $sort          = $request->get('sort');
        $status        = !is_null($request->get('status')) ? $request->get('status') : 0;
        $id            = !is_null($request->get('id')) ? $request->get('id') : 0;

        $newVipRule = VipRule::whereId($id)->first();
        if(!$newVipRule)
            $newVipRule = new VipRule();

        if(!is_null($name))$newVipRule->name       = $name;
        if(!is_null($type))$newVipRule->type       = $type;
        if(!is_null($free))$newVipRule->free       = $free;
        $newVipRule->price                         = $price;
        $newVipRule->original_price                = $originalPrice;
        if(!is_null($sort))$newVipRule->sort       = $sort;
        if(!is_null($status))$newVipRule->status   = $status;
        $newVipRule->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $newVipRule]);
    }

    public function delVipRule(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        $thatVipRule =VipRule::whereId($id)->first();

        if(!$thatVipRule)
            return response()->json(["level"=>"error","message"=>"该vip规则不存在！"]);

        $thatVipRule->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $thatVipRule]);
    }

    public function addSteelFormat(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $name          = $request->get("name");
        $type          = $request->get('type');
        $sort          = !is_null($request->get('sort')) ? $request->get('sort') : 0;
        $id            = !is_null($request->get('id')) ? $request->get('id') : 0;

        $newSteelFormat = SteelFormat::whereId($id)->first();
        if(!$newSteelFormat)
            $newSteelFormat = new SteelFormat();

        if(!is_null($name))$newSteelFormat->name             = $name;
        if(!is_null($type))$newSteelFormat->type             = $type;
        $newSteelFormat->sort                                = $sort;
        $newSteelFormat->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $newSteelFormat]);
    }

    public function delSteelFormat(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        $thatSteelFormat =SteelFormat::whereId($id)->first();

        if(!$thatSteelFormat)
            return response()->json(["level"=>"error","message"=>"该信息不存在！"]);

        $thatSteelFormat->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $thatSteelFormat]);

    }

    public function addFactoryCount(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $brandId           = !is_null($request->get('brand_id')) ? $request->get('brand_id') : 0;
        $formatId          = !is_null($request->get('format_id')) ? $request->get('format_id') : 0;
        $factoryCount      = !is_null($request->get('factory_count')) ? $request->get('factory_count') : 0;
        $id                = !is_null($request->get('id')) ? $request->get('id') : 0;

        $newSteelFormatAssociation = SteelFormatAssociation::whereId($id)->first();
        if(!$newSteelFormatAssociation)
            $newSteelFormatAssociation = new SteelFormatAssociation();

        if(!is_null($brandId))$newSteelFormatAssociation->brand_id               = $brandId;
        if(!is_null($formatId))$newSteelFormatAssociation->format_id             = $formatId;
        if(!is_null($factoryCount))$newSteelFormatAssociation->factory_count     = $factoryCount;
        $newSteelFormatAssociation->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $newSteelFormatAssociation]);
    }

    public function delFactoryCount(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        $thatSteelFormatAssociation = SteelFormatAssociation::whereId($id)->first();

        if(!$thatSteelFormatAssociation)
            return response()->json(["level"=>"error","message"=>"该信息不存在！"]);

        $thatSteelFormatAssociation->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $thatSteelFormatAssociation]);

    }

    public function delManagerUser(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $thisUser = User::whereId($id)->first();
        if(!$thisUser)
            return response()->json(['level' => 'error','message' => '该管理员不存在']);

        $thisUser->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $thisUser]);
    }

    public function setManagerUser(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $username   = $request->get('username');
        $password   = $request->get('password');
        $repass     = $request->get('repass');
        $id         =!is_null($request->get('id')) ? $request->get('id') :'';

        if($id!=''){
            $userId=User::whereId($id)->first();
            if($userId){
                $thatUser=$userId;
            } else{
                return response()->json(['level'=>'error','message'=>'该用户不存在！']);
            }
        } else{
            $thatUser = new User();
        }
        $isUsername = User::whereUsername($username)->first();
        if($isUsername && $isUsername->id != $id)
            return response()->json(['level' => 'error','message' => '用户名已存在']);

        if($password != $repass)
            return response()->json(['level' => 'error','message' => '两侧密码不一致']);

//        $thatUser = new User();

        if(!is_null($username))$thatUser->username = $username;
        if(!is_null($password))$thatUser->password = bcrypt($password);
        $thatUser->role = 2;
        $thatUser->save();

        $userInfo = Userinfo::whereUserId($thatUser->id)->first();
        if(!$userInfo)
            $userInfo = new Userinfo();

        $userInfo->user_id = $thatUser->id;
        $userInfo->save();

        return response()->json(["level"=>"success","message"=>"设置成功","data"=>$thatUser]);
    }

    public function bindingPermissions(Request $request){
        if(Auth::guard('admin')->guest())
            return response()->json(['level' => 'error','message' => '请先登录！']);

        $permissionIds = $request->get('permission_ids');
        $RoleId        = $request->get('role_id');

        $role = Role::whereId($RoleId)->first();
        if(!$role)
            return response()->json(['level' => 'error','message' => '该角色不存在']);

        DB::table('permission_role')->where('role_id',$role->id)->delete();

        if(count($permissionIds) > 0){
            foreach($permissionIds as $permissionId){
                $permissionRole = DB::table('permission_role')->insert(['role_id' => $RoleId,'permission_id' => $permissionId]);
            }
        }else{
            $permissionRole = null;
        }

        return response()->json(['level' => 'success','message' => '绑定成功','data' => $permissionRole]);
    }

    public function delRole(Request $request){
        if(Auth::guard('admin')->guest())
            return response()->json(['level' => 'error','message' => '请先登录！']);

        $id = !is_null($request->get('id')) ? $request->get('id')  : '';
        if ($id!=''){
            $role=Role::whereId($id)->first();
            if($role){
                $role->delete();
                return response()->json(['level'=>'success','message'=>'删除成功']);
            } else{
                return response()->json(['level'=>'error','message'=>'删除失败，没有这条记录']);
            }
        }

        return response()->json(['level'=>'error','message'=>'没有获取到你需要删除的角色']);
    }

    public function delPermissions(Request $request){
        if(Auth::guard('admin')->guest())
            return response()->json(['level' => 'error','message' => '请先登录！']);
        $id = !is_null($request->get('id')) ? $request->get('id') : '';
        if ($id!=''){
            $permission=DB::table('permission_role')->where('id',$id)->delete();
            if($permission){
                return response()->json(['level'=>'success','message'=>'删除成功']);
            } else {
                return response()->json(['level'=>'error','message'=>'删除失败，没有这个记录']);
            }
        } else
            return response()->json(['level'=>'error','message'=>'没有传入id']);
    }

    public function setPermissions(Request $request){
        if(Auth::guard('admin')->guest())
            return response()->json(['level' => 'error','message' => '请先登录！']);

        $name           = !is_null($request->get('name'))            ? $request->get('name')         : '';
        $display_name   = !is_null($request->get('display_name'))    ? $request->get('display_name') : '';
        $description    = !is_null($request->get('description'))     ? $request->get('description')  : '';
        $id             = !is_null($request->get('id'))              ? $request->get('id')           : '';

        if ($id!=''){
            $permission=Permission::whereId($id)->first();
        } else {
            $permission=new Permission();
        }
        if ($permission){
            if($name!='')
                $permission->name=$name;
            if($display_name!='')
                $permission->display_name=$display_name;
            if($description!='')
                $permission->description=$description;
            $permission->save();
            return response()->json(['level'=>'success','message'=>'设置成功']);
        } else {
            return response()->json(['level'=>'error','message'=>'设置失败']);
        }
    }

    public function setRole(Request $request){
        if(Auth::guard('admin')->guest())
            return response()->json(['level' => 'error','message' => '请先登录！']);

        $name           = !is_null($request->get('name'))            ? $request->get('name')         : '';
        $display_name   = !is_null($request->get('display_name'))    ? $request->get('display_name') : '';
        $description    = !is_null($request->get('description'))     ? $request->get('description')  : '';
        $id             = !is_null($request->get('id'))              ? $request->get('id')           : '';

        if ($id!=''){
            $role=Role::whereId($id)->first();
        } else {
            $role=new Role();
        }
        if ($role){
            if($name!='')
                $role->name=$name;
            if($display_name!='')
                $role->display_name=$display_name;
            if($description!='')
                $role->description=$description;
            $role->save();
            return response()->json(['level'=>'success','message'=>'设置成功']);
        } else {
            return response()->json(['level'=>'error','message'=>'设置失败']);
        }

    }

    /**
     * @author cmj
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function companySet(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id           =  !is_null($request->get('company_id')) ? $request->get('company_id') : '';
        $company_name =  !is_null($request->get('company_name')) ? $request->get('company_name') : '';
        $province     =  !is_null($request->get('province')) ? $request->get('province') : '';
        $city         =  !is_null($request->get('city')) ? $request->get('city') : '';
        $area         =  !is_null($request->get('area')) ? $request->get('area') : '';
        $info         =  !is_null($request->get('info')) ? $request->get('info') : '';
        $phone        =  !is_null($request->get('phone')) ? $request->get('phone') : '';
        $company_num  =  !is_null($request->get('company_num')) ? $request->get('company_num') : '';

        if($id!='' && $id!=0){
            $company=Company::whereId($id)->first();
            $company->company_name  =$company_name;
            $company->province      =$province;
            $company->city          =$city;
            $company->area          =$area;
            $company->info          =$info;
            $company->phone         =$phone;
            $company->company_num   =$company_num;
            $company->save();
            return response()->json(['level'=>'success','message'=>'修改成功！']);
        }
        else
        {
            if($company_name!='' && $province!='' && $city!='' && $area!='' && $info!='' && $phone!='' && $company_num!='')
            {
                $company=new Company();
                $company->company_name  =$company_name;
                $company->province      =$province;
                $company->city          =$city;
                $company->area          =$area;
                $company->info          =$info;
                $company->phone         =$phone;
                $company->company_num   =$company_num;
                $company->save();
                return response()->json(['level'=>'success','message'=>'添加成功！']);
            }

            return response()->json(['level'=>'error','message'=>'必填项不能为空']);
        }
    }

    /**@author cmj
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function companyDel(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $company_id=!is_null($request->get('company_id')) ? $request->get('company_id') : '';
        if($company_id!='' && $company_id!= 0)
        {
            $company=Company::whereId($company_id)->first();
            if($company)
                $company->delete();
            else
                return response()->json(['level'=>'error','message'=>'没有这家公司！']);
            return response()->json(['level'=>'success','message'=>'删除成功！']);
        }
        else
             return response()->json(['level'=>'error','message'=>'参数错误！！']);
    }

    /**
     * @author cmj
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     *
     */
    public function companyBind(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $company_id =!is_null($request->get('company_id'))  ? $request->get('company_id')   : '';
        $user_id    =!is_null($request->get('user_id'))     ? $request->get('user_id')      : '';
        if($company_id!=''){
            if($user_id!=''){
                $company_manager=new CompanyManager();
                $company_manager->company_id=$company_id;
                $company_manager->user_id=$user_id;
                $company_manager->save();
                return response()->json(['level'=>'success','message'=>'绑定成功！']);
            } else {
                return response()->json(['level'=>'error','message'=>'没有传入用户id']);
            }
        } else {
            return response()->json(['level'=>'error','message'=>'没有传入公司id']);
        }
    }

    /**
     * @author cmj
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function companyUnbind(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $company_id =!is_null($request->get('company_id'))  ? $request->get('company_id')   : '';
        $user_id    =!is_null($request->get('user_id'))     ? $request->get('user_id')      : '';
        $record_id  =!is_null($request->get('record_id'))   ? $request->get('record_id')    : '';
        if($company_id!=''){
            if($user_id!=''){
                $company=CompanyManager::whereUserId($user_id)->whereCompanyId($company_id)->first();
                if($company){
                    if($company->id==$record_id) {
                        $company->delete();
                        return response()->json(['level'=>'success','message'=>'解绑成功']);
                    }

                } else {
                    return response()->json(['level'=>'error','message'=>'发生错误！数据库没有这条记录哦，可能是已经解绑了']);
                }
            } else {
                return response()->json(['level'=>'error','message'=>'前端没有传入用户id啊！']);
            }
        } else
            return response()->json(['level'=>'error','message'=>'前端没有传入解绑的公司id啊！！']);
    }

    public function adminAllow(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $projectId= !is_null($request->get('project_id'))   ? $request->get('project_id')   : '';
        $type=      !is_null($request->get('type'))         ? $request->get('type')         : '';
        if ($projectId!=''){
            $thisProject=project::whereId($projectId)->first();
            if($thisProject){
                if($thisProject->manager_verify!=1){
                    if($type!='' && $type=='overwrite'){
                        $thisProject->admin_verify=1;
                        //$thisProject->manager_verify=3;
                        $projectUser=ProjectUsers::whereProjectId($projectId)->first();
                        if($projectUser){
                            $projectUser->user_id=$thisProject->user_id;
                            $projectUser->project_id=$thisProject->id;
                        }
                        else {
                            $projectUser = new ProjectUsers();
                            $projectUser->user_id=$thisProject->user_id;
                            $projectUser->project_id=$thisProject->id;
                        }
                        $projectUser->save();
                        $thisProject->save();
                        return response()->json(['level'=>'success','message'=>'直接批准成功！']);
                    } else{
                        return response()->json(['level'=>'error','message'=>'overwrite']);
                    }
                }
                $thisProject->admin_verify=1;
                $projectUser=ProjectUsers::whereProjectId($projectId)->first();
                if($projectUser){
                    $projectUser->user_id=$thisProject->user_id;
                }
                else {
                    $projectUser = new ProjectUsers();
                    $projectUser->user_id=$thisProject->user_id;
                    $projectUser->project_id=$thisProject->id;
                }
                $projectUser->save();
                $thisProject->save();
                return response()->json(['level'=>'success','message'=>'批准成功！']);
            }
        }
    }

    public function adminDeny(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $projectId= !is_null($request->get('project_id'))   ? $request->get('project_id')   : '';
        $type=      !is_null($request->get('type'))         ? $request->get('type')         : '';
        if ($projectId!=''){
            $thisProject=project::whereId($projectId)->first();
            if($thisProject){
                if($thisProject->manager_verify==1 || $thisProject->manager_verify==0 ||$thisProject->manager_verify==3){
                    if($type!='' && $type=='overwrite'){
                        $thisProject->admin_verify=2;
                        //$thisProject->manager_verify=4;
                        $projectUser=ProjectUsers::whereProjectId($projectId)->first();
                        if($projectUser){
                            $projectUser->delete();
                            $projectUser->save();
                        }
                        $thisProject->save();
                        return response()->json(['level'=>'success','message'=>'直接拒绝成功！']);
                    } else{
                        return response()->json(['level'=>'error','message'=>'overwrite']);
                    }
                } else if ($thisProject->manager_verify==2) {
                    if($thisProject->admin_verify==2){
                        return response()->json(['level'=>'success','message'=>'已拒绝！无需重复拒绝']);
                    }
                    $thisProject->admin_verify=2;
                    $thisProject->save();
                    return response()->json(['level'=>'success','message'=>'拒绝成功']);
                }
            }
        }
    }
}

